package com.jingtai.common.utils.random;

import com.jingtai.common.webfacade.error.CommonException;
import com.jingtai.common.webfacade.error.ErrorEnum;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {


    private final static String KEY = "LH34567@836943#1";

    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * base 64 encode
     */
    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * base 64 decode
     */
    private static byte[] base64Decode(String base64Code) throws Exception {
        return StringUtils.isEmpty(base64Code) ? null : Base64.getDecoder().decode(base64Code);
    }

    /**
     * 加密
     */
    public static String encrypt(String content) {
        return encrypt(content, KEY);
    }
    public static String encrypt(String content, String encryptKey) {
        try {
            Cipher cipher = getCipher(encryptKey);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
            byte[] result = cipher.doFinal(content.getBytes());
            return base64Encode(result);
        } catch (Exception e) {
            throw new CommonException(ErrorEnum.AES_CONVERT_ERROR);
        }

    }
    private static Cipher getCipher(String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        return cipher;
    }


    /**
     * 解密
     */
    public static String decrypt(String content) {
        return decrypt(content, KEY);
    }
    public static String decrypt(String content, String encryptKey) {
        try {
            Cipher cipher = getCipher(encryptKey);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
            byte[] result = cipher.doFinal(base64Decode(content));
            return new String(result);
        } catch (Exception e) {
            throw new CommonException(ErrorEnum.AES_CONVERT_ERROR);
        }

    }
}
